package com.agrm.address.controller;


import com.agrm.address.service.AddressService;
import com.agrm.address.service.ChinaRegionsService;
import com.agrm.model.address.pojo.Address;
import com.agrm.model.address.pojo.ChinaRegions;
import com.agrm.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/v1/address")
public class AddressController {


    @Autowired
    private ChinaRegionsService chinaRegionsService;
    @Autowired
    private AddressService addressService;


    @GetMapping("/regions/tree")
    public ResponseResult getRegionTree() {
        List<ChinaRegions> regionTree = chinaRegionsService.findTree();
        return ResponseResult.okResult(regionTree);
    }


    @GetMapping("/regions/tree/{id}")
    public ResponseResult getRegionTreeById(@PathVariable("id") Integer memberId) {
        if (memberId == null || memberId <= 0) {
            return ResponseResult.errorResult(400, "ID参数无效");
        }

        List<ChinaRegions> regionTree = chinaRegionsService.findSubTreeById(memberId);
        if (regionTree.isEmpty()) {
            return ResponseResult.errorResult(404, "未找到指定的地区信息");
        }

        return ResponseResult.okResult(regionTree);
    }


    @GetMapping("/get/{id}")
    public ResponseResult findById(@PathVariable("id") Integer memberId) {
        if (memberId == null || memberId <= 0) {
            return ResponseResult.errorResult(400, "ID参数无效");
        }

        List<Address> addresses = addressService.getByMemberId(memberId);
        if (addresses == null) {
            return ResponseResult.errorResult(404, "未找到指定的地址信息");
        }

        // 加载关联的地区信息
        for (Address address : addresses) {
            if (address.getRegionId() != null) {
                ChinaRegions region = chinaRegionsService.findById(address.getRegionId());
                address.setRegion(region);
            }
        }

        return ResponseResult.okResult(addresses);
    }


    @GetMapping("/getAll")
    public ResponseResult findAll() {
        List<Address> addresses = addressService.list();

        // 加载关联的地区信息
        loadRegionInfo(addresses);

        return ResponseResult.okResult(addresses);
    }

    // 辅助方法：加载地区信息
    private void loadRegionInfo(List<Address> addresses) {
        if (addresses == null || addresses.isEmpty()) {
            return;
        }

        Set<Integer> regionIds = addresses.stream()
                .map(Address::getRegionId)
                .filter(id -> id != null)
                .collect(Collectors.toSet());

        if (!regionIds.isEmpty()) {
            List<ChinaRegions> regions = chinaRegionsService.findAll();
            Map<Integer, ChinaRegions> regionMap = regions.stream()
                    .collect(Collectors.toMap(ChinaRegions::getId, region -> region));

            addresses.forEach(address -> {
                if (address.getRegionId() != null) {
                    ChinaRegions region = regionMap.get(address.getRegionId());
                    address.setRegion(region);
                }
            });
        }
    }


    @PostMapping("add")
    public ResponseResult add(@RequestBody Address address) {
        // 参数校验
        if (address == null) {
            return ResponseResult.errorResult(400, "地址信息不能为空");
        }

        // 执行保存
        boolean success = addressService.save(address);
        if (success) {
            return ResponseResult.okResult("地址添加成功");
        } else {
            return ResponseResult.errorResult(500, "地址添加失败");
        }
    }

    @PutMapping("update")
    public ResponseResult update(@RequestBody Address address) {
        // 参数校验
        if (address == null) {
            return ResponseResult.errorResult(400, "地址信息不能为空");
        }
        // 必要字段校验
        if (address.getId() == null || address.getId() <= 0) {
            return ResponseResult.errorResult(400, "地址ID不能为空");
        }

        // 必要字段校验

        if (address.getReceiver() == null || address.getReceiver().trim().isEmpty()) {
            return ResponseResult.errorResult(400, "收货人不能为空");
        }

        if (address.getPhone() == null || address.getPhone().trim().isEmpty()) {
            return ResponseResult.errorResult(400, "联系电话不能为空");
        }

        if (address.getRegionId() == null) {
            return ResponseResult.errorResult(400, "地区信息不能为空");
        }

        if (address.getRegionDetail() == null || address.getRegionDetail().trim().isEmpty()) {
            return ResponseResult.errorResult(400, "详细地址不能为空");
        }


        // 执行更新
        boolean success = addressService.updateById(address);
        if (success) {
            return ResponseResult.okResult("地址修改成功");
        } else {
            return ResponseResult.errorResult(500, "地址修改失败");
        }
    }


    /**
     * 批量删除地址
     *
     * @param ids 地址ID列表
     * @return 删除结果
     */
    @DeleteMapping("delete")
    public ResponseResult delete(@RequestBody List<Integer> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return ResponseResult.errorResult(400, "请选择要删除的地址");
        }

        // 验证ID有效性
        for (Integer memberId : ids) {
            if (memberId == null || memberId <= 0) {
                return ResponseResult.errorResult(400, "地址ID无效");
            }
        }

        // 检查地址是否存在
        List<Address> addresses = addressService.listByIds(ids);
        if (addresses.size() != ids.size()) {
            return ResponseResult.errorResult(404, "部分地址不存在");
        }

        // 执行删除
        boolean success = addressService.removeBatchByIds(ids);
        if (success) {
            return ResponseResult.okResult("地址删除成功");
        } else {
            return ResponseResult.errorResult(500, "地址删除失败");
        }
    }

    /**
     * 根据ID删除单个地址
     *
     * @param memberId 地址ID
     * @return 删除结果
     */
    @DeleteMapping("delete/{id}")
    public ResponseResult deleteById(@PathVariable("id") Integer memberId) {
        // 参数校验
        if (memberId == null || memberId <= 0) {
            return ResponseResult.errorResult(400, "地址ID无效");
        }

        // 检查地址是否存在
        Address address = addressService.getById(memberId);
        if (address == null) {
            return ResponseResult.errorResult(404, "未找到指定的地址信息");
        }

        // 执行删除
        boolean success = addressService.removeById(memberId);
        if (success) {
            return ResponseResult.okResult("地址删除成功");
        } else {
            return ResponseResult.errorResult(500, "地址删除失败");
        }
    }


}
